'use strict'

define(function (require, exports, module) {
    var angular = require('angular');
    var dialog = require("dialogplus");
    require("/public/js/plugins/select2/select2");
    var util = require("util");
    var api_prefix = G_CONFIG["api_prefix"]; //api前缀
    require('/public/js/myservice/contract/contract-common');
    var myMath = require('/public/js/myservice/common/my-math');
    var ContractReceivableFund = angular.module('ContractReceivableFund', ['ContractCommonService']);

    ContractReceivableFund.service('receivableFundService', ['$rootScope', 'contractCommonService', function ($rootScope, contractCommonService) {
        $rootScope.fundInfo = {};
        $rootScope.editFunds = [];

        var _receivable_amount;
        var _is_joint_sales = 0;

        var service = {
            onFundEditShow: function ($data, $dialog, $dialogScope, oldFund, isSplit,busnisseType,editmode) {
                /**
                 * 打开款项编辑界面时初始化
                 * oldFund: 原款项/被拆分款项
                 * isSplit: 是否拆分（如果为true则oldFund为被拆分款项）
                 */
                /*先处理下拉框数据*/
                //获取合同信息
                contractCommonService.getContract($data, function (data) {
                    if (data) {
                        $dialogScope.contractBaseInfo = data.contract;
                    }
                });

                $dialogScope.busnisseType = busnisseType;

                var execute_time = 0;
                //应收款名称下拉框
                $dialogScope.ddlConfigFundName = {
                    allowClear: false,
                    data: [],
                    placeholder: '应收款名称',
                    onchange2: function (newVal) {
                        if (execute_time % 2 == 0) {
                            contractCommonService.getFundSmallClass(newVal.id, function (data) {
                                var ddlData = [];
                                $.each(data, function (i, d) {
                                    ddlData.push({id: d.money_category_item_id, text: d.money_category_item_name});
                                });
                                $dialogScope.ddlConfigFundSmallClass.data = ddlData;
                                $dialogScope.$applyAsync();
                            });
                        }
                        execute_time++;
                    }
                };

                contractCommonService.getReceivableFundName(function (data) {
                    var ddlData = [];
                    $.each(data, function (i, d) {
                        ddlData.push({id: d.receivable_item_id, text: d.receivable_item_name});
                    });
                    $dialogScope.ddlConfigFundName.data = ddlData;
                    $dialogScope.$applyAsync();
                });

                //款项小类下拉框
                $dialogScope.ddlConfigFundSmallClass = {
                    allowClear: false,
                    data: [],
                    placeholder: '款项小类'
                };

                //收入类别
                $dialogScope.ddlConfigIncomeCategory = {
                    allowClear: false,
                    data: [],
                    placeholder: '核算收入类别',
                    onchange2: function (newVal, scope) {
                        if (scope) {
                            scope.type_name = newVal.text;
                        }
                    }
                };

                //获取核算收入类别下拉信息
                contractCommonService.getBussAccountTypes(function (data) {
                    var ddlData = [],
                        _initData;
                    $.each(data, function (i, d) {
                        ddlData.push({id: d.type_id, text: d.type_name});
                    });
                    $dialogScope.ddlConfigIncomeCategory.data = ddlData;
                    $dialogScope.$applyAsync();
                });
                //收款责任人下拉框
                $dialogScope.ddlConfigDutyOfficer = {
                    ajax: {
                        url: api_prefix + "erp-interface/get-users",
                        dataType: 'json',
                        delay: 250,
                        data: function (term) {
                            return {
                                keyword: term,
                                limit: 10
                            };
                        },
                        results: function (json, page) {
                            var data = [];
                            if (json.retCode === "0") {
                                data = json.data;
                            }
                            return {results: data};
                        },
                        escapeMarkup: function (markup) {
                            return markup;
                        },
                        cache: true
                    },
                    minimumInputLength: 1,
                    onchange2: function (newVal) {
                        $dialogScope.data.fundInfo.department_id = newVal.DepartmentId;
                        $dialogScope.data.fundInfo.department_name = newVal.DepartmentName;
                    }
                };

                var showJointSaler = function (is_joint_sales) {
                    if (is_joint_sales == 1) {
                        $('#label_joint_saler').removeClass('hide');
                        $('#div_joint_saler').removeClass('hide');
                    } else {
                        $('#label_joint_saler').addClass('hide');
                        $('#div_joint_saler').addClass('hide');
                        $('#joint_saler_error').addClass("ng-hide");
                        if (oldFund) {
                            oldFund.joint_saler_name = '';
                            oldFund.joint_saler = '';
                        }
                    }
                    _is_joint_sales = is_joint_sales;
                };

                oldFund && showJointSaler(oldFund.is_joint_sales);

                //是否联合销售
                $dialogScope.showJointSaler = function (is_joint_sales) {
                    showJointSaler(is_joint_sales);
                };

                //联合销售人下拉框
                $dialogScope.ddlConfigJointSaler = {
                    ajax: {
                        url: api_prefix + "erp-interface/get-users",
                        dataType: 'json',
                        delay: 250,
                        data: function (term) {
                            return {
                                keyword: term,
                                limit: 10
                            };
                        },
                        results: function (json, page) {
                            var data = [];
                            if (json.retCode === "0") {
                                data = json.data;
                            }
                            return {results: data};
                        },
                        escapeMarkup: function (markup) {
                            return markup;
                        },
                        cache: true
                    },
                    minimumInputLength: 1,
                    onchange2: function (newVal) {
                        if (newVal) {
                            $('#joint_saler_error').addClass("ng-hide");
                        }
                    }
                };

                $dialogScope.orgianlFund = oldFund;
                $dialogScope.isSplit = isSplit;
                $dialogScope.data.fundInfo = angular.extend({}, oldFund, {contract_id: $data});

                if (isSplit && $dialogScope.data.fundInfo) {
                    $dialogScope.data.fundInfo.old_receivable_id = $dialogScope.data.fundInfo.receivable_id;
                    $dialogScope.data.fundInfo.receivable_id = null;//如果是拆分款项，则为新增模式
                }
                if (oldFund) {
                    setTimeout(function () {
                        $('.idDutyOfficer:last').data('select2').updateSelection({text: oldFund.payee_name || oldFund.payee_id});
                    }, 0);
                    if (oldFund.joint_saler_name || oldFund.joint_saler) {
                        setTimeout(function () {
                            $('.idJointSaler:last').data('select2').updateSelection({text: oldFund.joint_saler_name || oldFund.joint_saler});
                        }, 0);
                    }
                } else {
                    setTimeout(function () {
                        $dialogScope.data.fundInfo.payee_id = $dialogScope.contractBaseInfo.sign_people_id;
                        $('.idDutyOfficer:last').data('select2').updateSelection({text: $dialogScope.contractBaseInfo.sign_people_name});
                    }, 0);

                    $dialogScope.data.fundInfo.department_id = $dialogScope.contractBaseInfo.sign_people_department_id;
                    $dialogScope.data.fundInfo.department_name = $dialogScope.contractBaseInfo.sign_people_department_name;

                    //获取收入
                    contractCommonService.getContractRevenue($data, function (data) {
                        if (data && data.revenueList && data.revenueList.length > 0) {
                            $dialogScope.data.fundInfo.revenue_type = data.revenueList[0].revenue_type;
                            $dialogScope.$applyAsync();
                        }
                    });
                }

                contractCommonService.getContractReceivable($data, function (data) {
                    /**
                     * 获取款项列表
                     */
                    _receivable_amount = 0;
                    $.each(data, function (i, d) {
                        _receivable_amount = myMath.add(_receivable_amount, d.receivable_amount);
                    });

                    $dialogScope.editFunds = data;
                    $dialogScope.$applyAsync();
                });

                if(editmode && editmode == '1'){
                    $dialogScope.data.fundInfo.contract_property = '0';
                    if(busnisseType == 4) {
                        $dialogScope.data.fundInfo.receivable_item_id = 'c211cbb4-5b11-11e7-9f96-000c29310f8b';
                    }
                    $dialogScope.$applyAsync();
                }
            },
            onFundEditChangePayeeShow: function ($data, $dialog, $dialogScope, oldFund) {
                /**
                 * 打开款项变更责任人界面时初始化
                 * oldFund: 原款项
                 */
                $dialogScope.data.fundInfo = angular.extend({}, oldFund, {contract_id: $data});
                //收款责任人下拉框
                $dialogScope.ddlConfigDutyOfficer = {
                    ajax: {
                        url: api_prefix + "erp-interface/get-users",
                        dataType: 'json',
                        delay: 250,
                        data: function (term) {
                            return {
                                keyword: term,
                                limit: 10
                            };
                        },
                        results: function (json, page) {
                            var data = [];
                            if (json.retCode === "0") {
                                data = json.data;
                            }
                            return {results: data};
                        },
                        escapeMarkup: function (markup) {
                            return markup;
                        },
                        cache: true
                    },
                    minimumInputLength: 1,
                    onchange2: function (newVal) {
                        $dialogScope.data.fundInfo.department_id = newVal.DepartmentId;
                        $dialogScope.data.fundInfo.department_name = newVal.DepartmentName;
                    }
                };
            },
            editFundSave: function ($data, $dialog, $dialogScope, callback) {
                $(".ui-dialog-autofocus").attr({"disabled":"disabled"});

                if (_is_joint_sales == 1 && $('#joint_saler').val() == '') {
                    $('#joint_saler_error').removeClass("ng-hide");
                    return false;
                } else {
                    $('#joint_saler_error').addClass("ng-hide");
                }

                /**
                 * 保存新增款项
                 */
                var fundInfo = $dialogScope.data.fundInfo;

                var post_data = fundInfo;
                var url;
                if ($dialogScope.isSplit) {
                    url = api_prefix + "/receivable/split-contract-receivalble";
                } else {
                    url = api_prefix + "/receivable/save-contract-receivable";
                }
                util.myAjax({
                    url: url,
                    type: "POST",
                    context: this,
                    data: post_data,
                    success: function (json) {
                        if (json.retCode == 0) {
                            util.alert("保存成功");
                            if (callback) {
                                callback();
                            }

                            $dialog.close();
                        } else {
                            util.alert("保存失败：" + json.errMsg);
                        }
                    }
                });
                return false;
            },
            changePayee: function ($data, $dialog, $dialogScope, callback) {
                /**
                 * 变更责任人
                 */
                var fundInfo = $dialogScope.data.fundInfo;
                //校验
                if (fundInfo.payee_id == $data.fundInfo.payee_id_new) {
                    util.alert('新责任人和原责任人相同');
                    return false;
                }

                fundInfo.payee_id = fundInfo.payee_id_new;

                var post_data = fundInfo;
                var url;
                url = api_prefix + "/receivable/change-responsible-person";

                util.myAjax({
                    url: url,
                    type: "POST",
                    context: this,
                    data: post_data,
                    success: function (json) {
                        if (json.retCode == 0) {
                            util.alert("责任人变更成功");
                            if (callback) {
                                callback();
                            }
                        } else {
                            util.alert("责任人变更失败：" + json.errMsg);
                        }
                    }
                });
            },
            changeReceivableDate: function ($data, $dialog, $dialogScope, callback) {
                /**
                 * 变更应收日期
                 */
                var fundInfo = $dialogScope.data.fundInfo;
                //校验
                if (fundInfo.receivable_date == $data.receivable_date_new) {
                    util.alert('新应收日期和原应收日期相同');
                    return false;
                }
                fundInfo.receivable_date = fundInfo.receivable_date_new;

                var post_data = fundInfo;
                var url;
                url = api_prefix + "/receivable/change-receivable-date";

                util.myAjax({
                    url: url,
                    type: "POST",
                    context: this,
                    data: post_data,
                    success: function (json) {
                        if (json.retCode == 0) {
                            util.alert("应收日期变更成功");
                            if (callback) {
                                callback();
                            }
                        } else {
                            util.alert("应收日期变更失败：" + json.errMsg);
                        }
                    }
                });
            },
            deleteFund: function (fundInfo) {
                /**
                 * 删除款项
                 */
                util.confirm('确定要删除此款项吗?', {
                    ok: function () {
                        var post_data = {receivable_id: fundInfo.receivable_id};
                        var url;
                        url = api_prefix + "/receivable/delete-contract-receivable";

                        util.myAjax({
                            url: url,
                            type: "POST",
                            context: this,
                            data: post_data,
                            success: function (json) {
                                if (json.retCode == 0) {
                                    fundInfo.__isdelete = 1;
                                    util.alert("删除成功");
                                    $rootScope.$applyAsync();
                                } else {
                                    util.alert("删除失败：" + json.errMsg);
                                }
                            }
                        });
                    }
                });
            },
            markOperation: function (fundInfo, isOperation, callback) {
                /**
                 * 设置运营关注款
                 */
                var post_data = {receivable_id: fundInfo.receivable_id, is_operation: isOperation};
                var url;
                url = api_prefix + "/receivable/mark-operation";

                util.myAjax({
                    url: url,
                    type: "POST",
                    context: this,
                    data: post_data,
                    success: function (json) {
                        if (json.retCode == 0) {
                            if (callback) {
                                callback();
                            }
                            util.alert(isOperation ? "设置运营关注款成功" : "取消运营关注款成功");
                        } else {
                            util.alert((isOperation ? "设置运营关注款失败：" : "取消运营关注款失败：") + json.errMsg);
                        }
                    }
                });
            },
            markBadBebt: function (fundInfo, isBad, callback) {
                /**
                 * 标记坏账
                 */
                var post_data = {receivable_id: fundInfo.receivable_id, is_bad_debt: isBad};
                var url;
                url = api_prefix + "/receivable/mark-bad-debt";

                util.myAjax({
                    url: url,
                    type: "POST",
                    context: this,
                    data: post_data,
                    success: function (json) {
                        if (json.retCode == 0) {
                            if (callback) {
                                callback();
                            }
                            util.alert(isBad ? "标记为坏账成功" : "取消标记坏账成功");
                        } else {
                            util.alert((isBad ? "标记为坏账失败：" : "取消标记坏账失败：") + json.errMsg);
                        }
                    }
                });
            },
            markBadBebtConfim: function (fundInfo, isBad, callback) {
                var that = this;
                util.confirm(isBad ? '是否标记为坏账' : '是否取消标记坏账', {
                    ok: function () {
                        that.markBadBebt(fundInfo, isBad, callback);
                    }
                });
            }
        };
        return service;
    }]);

    module.exports = ContractReceivableFund;
});